package com.example.appointment.service.impl;

import com.example.appointment.dto.ActivityRegistrationDTO;
import com.example.appointment.dto.ClubActivityDTO;
import com.example.appointment.entity.ClubActivity;
import com.example.appointment.entity.User;
import com.example.appointment.exception.ResourceNotFoundException;
import com.example.appointment.repository.ActivityRegistrationRepository;
import com.example.appointment.repository.ClubActivityRepository;
import com.example.appointment.repository.UserRepository;
import com.example.appointment.service.ActivityRegistrationService;
import com.example.appointment.service.ClubActivityService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 社团活动服务实现类
 */
@Service
public class ClubActivityServiceImpl implements ClubActivityService {

    @Autowired
    private ClubActivityRepository activityRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private ActivityRegistrationService registrationService;
    
    @Autowired
    private ActivityRegistrationRepository registrationRepository;

    @Override
    @Transactional
    public ClubActivityDTO createActivity(ClubActivityDTO activityDTO, Long userId) {
        User creator = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));

        ClubActivity activity = new ClubActivity();
        BeanUtils.copyProperties(activityDTO, activity);
        activity.setCreatedBy(creator);
        activity.setIsActive(true);
        activity.setCurrentParticipants(0);
        
        // 保存活动
        ClubActivity savedActivity = activityRepository.save(activity);
        
        // 复制回DTO
        ClubActivityDTO resultDTO = new ClubActivityDTO();
        BeanUtils.copyProperties(savedActivity, resultDTO);
        resultDTO.setCreatedById(creator.getId());
        resultDTO.setCreatedByName(creator.getName());
        
        return resultDTO;
    }

    @Override
    @Transactional
    public ClubActivityDTO updateActivity(Long id, ClubActivityDTO activityDTO) {
        ClubActivity activity = activityRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("活动不存在"));

        // 更新可编辑的字段
        activity.setTitle(activityDTO.getTitle());
        activity.setDescription(activityDTO.getDescription());
        activity.setStartTime(activityDTO.getStartTime());
        activity.setEndTime(activityDTO.getEndTime());
        activity.setLocation(activityDTO.getLocation());
        activity.setMaxParticipants(activityDTO.getMaxParticipants());
        activity.setImageUrl(activityDTO.getImageUrl());
        
        // 保存更新
        ClubActivity updatedActivity = activityRepository.save(activity);
        
        // 复制回DTO
        ClubActivityDTO resultDTO = new ClubActivityDTO();
        BeanUtils.copyProperties(updatedActivity, resultDTO);
        resultDTO.setCreatedById(updatedActivity.getCreatedBy().getId());
        resultDTO.setCreatedByName(updatedActivity.getCreatedBy().getName());
        
        return resultDTO;
    }

    @Override
    public ClubActivityDTO getActivityById(Long id, Long currentUserId) {
        ClubActivity activity = activityRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("活动不存在"));

        ClubActivityDTO activityDTO = new ClubActivityDTO();
        BeanUtils.copyProperties(activity, activityDTO);
        activityDTO.setCreatedById(activity.getCreatedBy().getId());
        activityDTO.setCreatedByName(activity.getCreatedBy().getName());
        
        // 检查当前用户是否已报名
        if (currentUserId != null) {
            boolean isRegistered = registrationService.isUserRegistered(id, currentUserId);
            activityDTO.setIsRegistered(isRegistered);
        } else {
            activityDTO.setIsRegistered(false);
        }
        
        // 获取评价统计
        List<ActivityRegistrationDTO> feedbacks = registrationService.getActivityFeedbacks(id);
        if (!feedbacks.isEmpty()) {
            double averageRating = feedbacks.stream()
                    .filter(f -> f.getRating() != null)
                    .mapToInt(ActivityRegistrationDTO::getRating)
                    .average()
                    .orElse(0.0);
            activityDTO.setAverageRating(averageRating);
            activityDTO.setFeedbackCount(feedbacks.size());
        } else {
            activityDTO.setAverageRating(0.0);
            activityDTO.setFeedbackCount(0);
        }
        
        return activityDTO;
    }

    @Override
    public Page<ClubActivityDTO> getActiveActivities(Pageable pageable, Long currentUserId) {
        Page<ClubActivity> activitiesPage = activityRepository.findByIsActiveTrueAndEndTimeAfter(
                LocalDateTime.now(), pageable);

        return activitiesPage.map(activity -> convertToDTO(activity, currentUserId));
    }

    @Override
    public Page<ClubActivityDTO> getAllActivities(Pageable pageable) {
        // 查询所有活动，包括已取消的
        Page<ClubActivity> activitiesPage = activityRepository.findAll(pageable);
        
        return activitiesPage.map(activity -> {
            ClubActivityDTO dto = new ClubActivityDTO();
            BeanUtils.copyProperties(activity, dto);
            dto.setCreatedById(activity.getCreatedBy().getId());
            dto.setCreatedByName(activity.getCreatedBy().getName());
            return dto;
        });
    }

    @Override
    public Page<ClubActivityDTO> searchActivities(String keyword, Pageable pageable, Long currentUserId) {
        Page<ClubActivity> activitiesPage = activityRepository.findByIsActiveTrueAndTitleContainingOrDescriptionContaining(
                keyword, keyword, pageable);

        return activitiesPage.map(activity -> convertToDTO(activity, currentUserId));
    }

    @Override
    public List<ClubActivityDTO> getActivitiesByCreator(Long userId) {
        List<ClubActivity> activities = activityRepository.findByCreatedById(userId);
        
        return activities.stream()
                .map(activity -> convertToDTO(activity, userId))
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void cancelActivity(Long id) {
        ClubActivity activity = activityRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("活动不存在"));
        
        activity.setIsActive(false);
        activityRepository.save(activity);
    }

    @Override
    @Transactional
    public void deleteActivity(Long id) {
        ClubActivity activity = activityRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("活动不存在"));
        
        activityRepository.delete(activity);
    }
    
    /**
     * 将实体转换为DTO
     */
    private ClubActivityDTO convertToDTO(ClubActivity activity, Long currentUserId) {
        ClubActivityDTO dto = new ClubActivityDTO();
        BeanUtils.copyProperties(activity, dto);
        
        dto.setCreatedById(activity.getCreatedBy().getId());
        dto.setCreatedByName(activity.getCreatedBy().getName());
        
        // 设置是否已报名
        if (currentUserId != null) {
            boolean isRegistered = registrationService.isUserRegistered(activity.getId(), currentUserId);
            dto.setIsRegistered(isRegistered);
        } else {
            dto.setIsRegistered(false);
        }
        
        return dto;
    }
} 